using SqlSugar;
using Viyi.Util.Extensions;

namespace JamesFan.FetchAreaCodes.Repository;

internal abstract class AbstractRepository {
    protected virtual SqlSugarScope Db => db!;
    SqlSugarScope? db;

    readonly ConnectionConfig config;

    protected AbstractRepository(ConnectionConfig config) {
        this.config = config;
    }

    public virtual AbstractRepository Initialize() {
        db = new SqlSugarScope(config).Also(db => {
            db.Aop.OnLogExecuting = (sql, _) => WriteLine($"[SQL] {sql}");
        });
        Migrate();

        Db.Deleteable<AreaCode>().ExecuteCommand();

        return this;
    }

    protected virtual void Migrate() {
        db!.CodeFirst.Also(ctx => {
            ctx.SetStringDefaultLength(255);
            ctx.InitTables<AreaCode>();
        });
    }

    public virtual void AddEntry(CodeEntry entry) {
        Db.Insertable(entry.ToEntity()).ExecuteCommand();
    }

    public virtual void AddEntities(IEnumerable<CodeEntry> entries) {
        var list = entries.Select(it => it.ToEntity()).ToList();
        Db.Insertable(list).ExecuteCommand();
    }
}
